package com.jiepos.mpos.inter.intopieces.utils;

import java.lang.reflect.Field;

import com.jiepos.mpos.common.constant.ExceptionConstant;
import com.jiepos.mpos.core.exception.MposException;
import com.jiepos.mpos.core.util.StringUtils;
import com.jiepos.mpos.inter.intopieces.stereotype.FieldFilter;

/**
 * @ClassName: FieldFilterUtils
 * @Description: FieldFilter注解的字段验证
 * @author 孙永
 * @date 2018年2月12日 上午9:53:05
 */
public class FieldFilterUtils {

	/**
	 * 字段过滤验证
	 * @param clz 验证的类
	 * @param object 验证的对象
	 * @throws Exception
	 */
	public static void fieldFilter(Class<?> clz, Object object) throws Exception{
		Field[] fields = clz.getDeclaredFields();
		for(Field field : fields){
			/*有字段过滤的注解*/
			if(field.isAnnotationPresent(FieldFilter.class)){
				FieldFilter fieldFilter = field.getAnnotation(FieldFilter.class);
				String name = fieldFilter.name(); // 字段名称
				if(StringUtils.isBlank(name)){
					throw new MposException(ExceptionConstant.MER_ERROR, name);
				}
				field.setAccessible(true);// 设置为public访问属性
				Object value = field.get(object);
				boolean required = fieldFilter.required(); // 是否必需
				if(required && isEmpty(value)){
					throw new MposException(ExceptionConstant.MER_NULL, name);
				}
				boolean number = fieldFilter.number(); // 是否为数值
				if(number && !isNumber(value)){
					throw new MposException(ExceptionConstant.MER_NOT_NUMBER, name);
				}
				int fixedLength = fieldFilter.fixedLength(); // 固定长度
				if(fixedLength > 0 && !isEmpty(value) && value.toString().length() != fixedLength){
					throw new MposException(ExceptionConstant.MER_NOT_FOLLOW_LENGTH, name);
				}
				int maxLength = fieldFilter.maxLength(); // 最大长度
				if(!isEmpty(value) && value.toString().length() > maxLength){
					throw new MposException(ExceptionConstant.MER_TOO_LENGTH, name);
				}
			}
		}
	}

	/**
	 * 验证对象的值是否为空
	 * @param object 验证对象
	 * @return
	 */
	private static boolean isEmpty(Object object){
		if(object == null || "".equals(object)){
			return true;
		}
		return false;
	}
	
	/**
	 * 验证对象的值是否为纯数字
	 * @param object 验证对象
	 * @return
	 */
	private static boolean isNumber(Object object){
		if(object != null){
			return isEmpty(object.toString().replaceAll("[0-9]", ""));
		}
		return true;
	}

}
